package com.neusoft.hifly.lock.strategy.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.redisson.config.Config;

import com.neusoft.hifly.lock.config.RedissonConfig;
import com.neusoft.hifly.lock.constant.GlobalConstant;
import com.neusoft.hifly.lock.strategy.RedissonConfigService;
import com.neusoft.hifly.lock.utils.Log;

/**
 * 主从部署Redisson配置
 * <p>
 * 连接方式: 主节点,子节点,子节点 格式为: 127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381
 */
public class MasterslaveConfigImpl implements RedissonConfigService {
	/**
	 * 根据不同的Redis配置策略创建对应的Config
	 *
	 * @param redissonProperties
	 *            redisson配置
	 * @return Config
	 */
	@Override
	public Config createRedissonConfig(final RedissonConfig redissonProperties) {
		final Config config = new Config();
		try {
			final String address = redissonProperties.getAddress();
			final String password = redissonProperties.getPassword();
			final int database = redissonProperties.getDatabase();
			final String[] addrTokens = address.split(",");
			final String masterNodeAddr = addrTokens[0];
			//设置主节点ip
			config.useMasterSlaveServers().setMasterAddress(masterNodeAddr);
			if (StringUtils.isNotBlank(password)) {
				config.useMasterSlaveServers().setPassword(password);
			}
			config.useMasterSlaveServers().setDatabase(database);
			//设置从节点，移除第一个节点，默认第一个为主节点
			final List<String> slaveList = new ArrayList<>();
			for (final String addrToken : addrTokens) {
				slaveList.add(GlobalConstant.REDIS_CONNECTION_PREFIX.getConstantValue() + addrToken);
			}
			slaveList.remove(0);

			config.useMasterSlaveServers().addSlaveAddress((String[]) slaveList.toArray());
			Log.info("初始化[主从部署]方式Config,redisAddress:" + address);
		} catch (final Exception e) {
			Log.info("主从部署 Redisson init error", e);
			e.printStackTrace();
		}
		return config;
	}

}
